<%@ page import="com.example.util.DBUtil" %>
<%@ page import="com.example.dao.PasswordResetDao" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    request.setCharacterEncoding("UTF-8");
    String token = request.getParameter("token");
    String password = request.getParameter("password");
    String confirmPassword = request.getParameter("confirm_password");
    
    // 检查参数是否为空
    if (token == null || token.trim().isEmpty() || 
        password == null || password.trim().isEmpty() || 
        confirmPassword == null || confirmPassword.trim().isEmpty()) {
        request.setAttribute("error", "所有字段都是必填的");
    } else if (!password.equals(confirmPassword)) {
        request.setAttribute("error", "两次输入的密码不一致");
    } else if (password.length() < 6) {
        request.setAttribute("error", "密码长度不能少于6位");
    } else {
        try {
            PasswordResetDao passwordResetDao = new PasswordResetDao();
            
            // 验证令牌
            PasswordResetDao.PasswordResetToken resetToken = passwordResetDao.findToken(token);
            if (resetToken == null) {
                request.setAttribute("error", "重置链接无效或已过期");
            } else {
                // 更新用户密码
                passwordResetDao.updatePassword(resetToken.getUserId(), password);
                
                // 标记令牌为已使用
                passwordResetDao.markTokenAsUsed(resetToken.getId());
                
                request.setAttribute("success", "密码重置成功，请使用新密码登录");
            }
        } catch (Exception e) {
            request.setAttribute("error", "系统错误: " + e.getMessage());
        }
    }
    
    // 根据结果转发到相应页面
    if (request.getAttribute("error") != null) {
        request.setAttribute("token", token);
        request.getRequestDispatcher("reset_password.jsp").forward(request, response);
    } else if (request.getAttribute("success") != null) {
        request.getRequestDispatcher("reset_password.jsp").forward(request, response);
    }
%>